package com.wangcang.widgetlibrary.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.activity.base.BaseActivity;
import com.wangcang.widgetlibrary.eventbus_event.ScanResultEvent;
import com.wangcang.widgetlibrary.tools.ToastUtils;
import com.wangcang.widgetlibrary.zxing.CameraManager;
import com.wangcang.widgetlibrary.zxing.CaptureActivityHandler;
import com.wangcang.widgetlibrary.zxing.InactivityTimer;
import com.wangcang.widgetlibrary.zxing.ScanningImageTools;
import com.wangcang.widgetlibrary.zxing.ViewfinderView;

import java.io.IOException;
import java.util.Vector;

import de.greenrobot.event.EventBus;

/**
 * @ClassName: CaptureActivity
 * @Description: 二维码扫描
 * @author juns
 * @date 2013-8-14
 */
public class CaptureActivity extends BaseActivity implements Callback {

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private boolean vibrate;
	Handler mHandler = null;

	private TextView mTitle;
	private ImageView mGoHome;

	ImageView lightBt = null; // 闪光灯按钮
	ImageView selectImgBt = null; // 选择图片按钮

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_code_scan);
		initView();
	}

	private void initView() {
		CameraManager.init(getApplication());
		mHandler = new Handler();
		initControl();
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void initControl() {
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		mTitle = (TextView) findViewById(R.id.common_title_msg);
		mTitle.setText("扫一扫");
		mGoHome = (ImageView) findViewById(R.id.img_back);
		mGoHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
				overridePendingTransition(R.anim.comm_scale_in, R.anim.comm_slide_out_to_right);
			}
		});

		lightBt = (ImageView) findViewById(R.id.light_bt);
		selectImgBt = (ImageView) findViewById(R.id.select_img);

		lightBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CameraManager.get().toggleLight();
			}
		});

		selectImgBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Intent intent = new Intent();
//				intent.setType("image/*");
//    			/* 使用Intent.ACTION_GET_CONTENT这个Action */
//				intent.setAction(Intent.ACTION_GET_CONTENT);
//   				/* 取得相片后返回本画面 */
//				startActivityForResult(intent, 1);

				Intent intent = new Intent(CaptureActivity.this, SelectImageActivity.class);
				startActivityForResult(intent, 1);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == 1) {
			String path = data.getExtras().getString(SelectImageActivity.SELECT_IMAGE_PATH);

			ScanningImageTools.scanningImage(path, new ScanningImageTools.IZCodeCallBack() {

				@Override
				public void ZCodeCallBackUi(Result result) {
					// TODO Auto-generated method stub
					if (result == null) {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								ToastUtils.showToast("未识别到二维码");
							}
						});
					} else {
						// 数据返回进行仿乱码处理
						final String recode = ScanningImageTools.recode(result.toString());
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								EventBus.getDefault().post(new ScanResultEvent(recode));
								finish();
							}
						});
					}

				}
			});
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;
		vibrate = true;
	}

	@Override
	public void onPause() {
		super.onPause();
		try {
			if (handler != null) {
				handler.quitSynchronously();
				handler = null;
			}
			CameraManager.get().closeDriver();
		}
		catch (Exception e) {

		}
	}

	@Override
	public void onDestroy() {
		if (inactivityTimer != null)
			inactivityTimer.shutdown();
		super.onDestroy();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(CaptureActivity.this, decodeFormats, characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	public void handleDecode(com.google.zxing.Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
//		Intent it = new Intent();
//		it.putExtra("RESULT", result.getText());
//		setResult(RESULT_OK, it);
//		finish();

		EventBus.getDefault().post(new ScanResultEvent(result.getText()));
		finish();
	}
}
